package edu.jxut.reggie.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.jxut.reggie.dtos.DishDto;
import edu.jxut.reggie.mapper.DishMapper;
import edu.jxut.reggie.pojos.Category;
import edu.jxut.reggie.pojos.Dish;
import edu.jxut.reggie.pojos.DishFlavor;
import edu.jxut.reggie.server.CategoryService;
import edu.jxut.reggie.server.DishFlavorService;
import edu.jxut.reggie.server.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;



    /**
     * 新增菜品，同时保存对应的口味数据
     * @param dishDto
     */
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {

        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);

        Long dishId = dishDto.getId();//菜品id

        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);

        //清除缓存
        String redisKey="DISH_"+dishDto.getCategoryId();

        redisTemplate.delete(redisKey);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息，从dish表查询
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        //查询当前菜品对应的口味信息，从dish_flavor表查询
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);

        return dishDto;
    }

    public List<DishDto> getByIdWithFlavor(List<Long> ids) {
        List<Dish> dishes = dishMapper.selectList(new LambdaQueryWrapper<Dish>().in(Dish::getId, ids));
        ArrayList<DishDto> dishDtos = new ArrayList<>();


        dishes.stream().forEach((dish) -> {
            DishDto dishDto = new DishDto();

            List<DishFlavor> list = dishFlavorService.list(new LambdaQueryWrapper<DishFlavor>().in(DishFlavor::getDishId, dish.getId()));

            BeanUtils.copyProperties(dish,dishDto);
            dishDto.setFlavors(list);
            dishDtos.add(dishDto);

        });

        return dishDtos;
    }



    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //更新dish表基本信息
        this.updateById(dishDto);

        //清理当前菜品对应口味数据---dish_flavor表的delete操作
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(queryWrapper);

        //添加当前提交过来的口味数据---dish_flavor表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

        //删除缓存
        String redisKey="DISH_"+dishDto.getCategoryId();
        redisTemplate.delete(redisKey);
    }

    @Override
    public Page<DishDto> findByPage(Integer page, Integer PageSize,String name) {
        Page<Dish> dishPage = new Page<>();
        Page<DishDto> dishDtoPage = new Page<>();
        dishPage.setPages(page);
        dishPage.setSize(PageSize);
        Page<Dish> dishPage1 = dishMapper.selectPage(dishPage, new LambdaQueryWrapper<Dish>()
                .like((StringUtils.isNotBlank(name)), Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime));

        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<Dish> records = dishPage1.getRecords();
        List<DishDto> collect = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(collect);
        return dishDtoPage;
    }

    @Override
    public List<DishDto> getByCateIdWithFlavor(Long cateId) {

        String redisKey="DISH"+"_"+cateId;
        ArrayList<DishDto> list= (ArrayList<DishDto>) redisTemplate.opsForValue().get(redisKey);

        if (list==null){
            ArrayList<DishDto> dishDtos = new ArrayList<>();
            List<Dish> dishes = dishMapper.selectList(new LambdaQueryWrapper<Dish>().eq(Dish::getCategoryId, cateId));
            for (Dish dish : dishes) {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish,dishDto);

                LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DishFlavor::getDishId,dish.getId());
                List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);

                dishDto.setFlavors(flavors);
                dishDtos.add(dishDto);
            }
            //添加缓存
            redisTemplate.opsForValue().set(redisKey,dishDtos,30, TimeUnit.MINUTES);
            return dishDtos;
        }
        return list;
    }

    @Transactional
    @Override
    public void rmIds(String ids) {
        String[] split = ids.split("\\,");
        List<Long> id = Arrays.stream(split).map(s -> Long.parseLong(s)).collect(Collectors.toList());
        this.removeByIds(id);
        dishFlavorService.remove(new LambdaQueryWrapper<DishFlavor>().in(DishFlavor::getDishId,id));
    }
}
